<template>
  <div 
    @click="onHeaderClick" 
    :class="headCls">
    <span 
      :class="[prefixCls + '-prefix']" 
      v-if="showPrefix">
      <slot name="prefix">
        <Icon 
          :type="prefix" 
          v-if="prefix" />
      </slot>
    </span>
    <span
      :class="singleDisplayClasses"
      v-show="!multiple && singleDisplayValue"
    >{{ singleDisplayValue }}</span>
    <div 
      :class="[prefixCls + '-head-sum']"
      :v-if="multiple">
      <span
        :class="singleDisplayClasses"
        v-show="multiple && singleDisplayValue"
      >{{ singleDisplayValue }}</span>
      <div :class="[prefixCls + '-mutiple-tag']">
        <Tag
          :class="tagPrefixCls + '-tag-no-border'"
          v-for="(item) in selectedMultiple"
          :key="item.value" 
          size="small" 
          status="suspend" 
          closable
          @close="removeTag(item, $event)">
          <span 
            :class="[tagPrefixCls + '-tag-text', item.disabled ? 'haloe-select-multiple-tag-hidden' : '']">
            {{ item.tag !== undefined ? item.tag : item.label }}
          </span>
        </Tag>
        <Tag 
          :class="tagPrefixCls + '-tag-no-border'"
          :key="more"
          size="small" 
          status="suspend" 
          v-if="limited !== undefined && values.length > limited"
        >
          <span :class="[tagPrefixCls + '-tag-text', prefixCls + '-max-tag']">
            <template v-if="maxTagPlaceholder">{{ maxTagPlaceholder(values.length - limited) }}</template>
            <template v-else>+ {{ values.length - limited }}...</template>
          </span>
        </Tag>
        <input
          :id="inputElementId"
          type="text"
          v-if="filterable"
          v-model="query"
          :disabled="disabled"
          :class="[prefixCls + '-input']"
          :placeholder="showPlaceholder ? localePlaceholder : ''"
          :style="inputStyle"
          autocomplete="off"
          spellcheck="false"
          @keydown="resetInputState"
          @keydown.delete="handleInputDelete"
          @keydown.enter="handleInputEnter"
          @focus="onInputFocus"
          @blur="onInputBlur"
          ref="input">
      </div>
      <span 
        v-if="limited !== undefined && multiple"
        :class="[prefixCls + '-suffix']">
        <span>{{selectedMultiple.length}}/{{ limited }}</span>
      </span>
    </div>
    <Icon 
      type="clear" 
      :class="[prefixCls + '-arrow']" 
      v-if="resetSelect" 
      @click.stop="onClear"></Icon>
    <Icon 
      :type="arrowType" 
      :custom="customArrowType" 
      :size="arrowSize" 
      :class="[prefixCls + '-arrow']" 
      v-if="!resetSelect && !remote"/>
  </div>
</template>
<script>
import { nextTick, toRaw } from 'vue';
import Icon from '../icon';
import Tag from '../tag';
import Locale from '../../mixins/locale';
import Emitter from '../../mixins/emitter'
import globalConfig from '../../mixins/globalConfig';
const prefixCls = 'haloe-select';
export default {
  name: 'eSelectHead',
  mixins: [ Emitter, Locale, globalConfig ],
  components: { 
    Icon,
    Tag
  },
  emits: ['on-input-focus', 'on-input-blur', 'on-keydown', 'on-enter', 'on-clear', 'on-query-change'],
  inject: ['SelectInstance', 'onRemoveTag'],
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    remote: {
      type: Boolean,
      default: false
    },
    initialLabel: {
      type: [String, Number, Array],
    },
    values: {
      type: Array,
      default: () => []
    },
    clearable: {
      type: [Function, Boolean],
      default: false,
    },
    inputElementId: {
      type: String
    },
    placeholder: {
      type: String
    },
    queryProp: {
      type: String,
      default: ''
    },
    prefix: {
      type: String
    },
    // 3.4.0
    limited: { // 多选时最多显示多少个 tag
      type: Number
    },
    // 3.4.0
    maxTagPlaceholder: {
      type: Function
    },
    // 4.0.0
    allowCreate: {
      type: Boolean
    },
    // 4.0.0
    showCreateItem: {
      type: Boolean
    }
  },
  data () {
    return {
      prefixCls: prefixCls,
      query: '',
      inputLength: 20,
      remoteInitialLabel: this.initialLabel,
      preventRemoteCall: false,
      tagPrefixCls: 'e'
    };
  },
  computed: {
    singleDisplayClasses () {
      const { filterable, multiple, showPlaceholder } = this;
      return [{
        [prefixCls + '-head-with-prefix']: this.showPrefix,
        [prefixCls + '-placeholder']: showPlaceholder && !filterable,
        [prefixCls + '-selected-value']: !showPlaceholder && !multiple && !filterable,
      }];
    },
    singleDisplayValue () {
      if ((this.multiple && this.values.length > 0) || this.filterable) return '';
      return `${this.selectedSingle}` || this.localePlaceholder;
    },
    showPlaceholder () {
      let status = false;
      if (!this.multiple) {
        const value = this.values[0];
        if (typeof value === 'undefined' || String(value).trim() === ''){
          status = !this.remoteInitialLabel;
        }
      } else {
        if (!this.values.length > 0) {
          status = true;
        }
      }
      return status;
    },
    resetSelect () {
      return !this.showPlaceholder && this.clearable;
    },
    inputStyle () {
      let style = {};
      if (this.multiple) {
        if (this.showPlaceholder) {
          style.width = '100%';
        } else {
          style.width = `${this.inputLength}px`;
        }
      }
      return style;
    },
    localePlaceholder () {
      if (this.placeholder === undefined) {
        return this.t('i.select.placeholder');
      } else {
        return this.placeholder;
      }
    },
    selectedSingle () {
      const selected = this.values[0];
      return selected ? selected.label : (this.remoteInitialLabel || '');
    },
    selectedMultiple () {
      const values = this.multiple ? this.values : [];
      const a = values.filter((item, index) => this.limited === undefined || index < this.limited);;
      // console.log("this.limited", this.limited, "--", a)
      return a
    },
    // 使用 prefix 时，在 filterable
    headCls () {
      return {
        [`${prefixCls}-head-flex`]: this.filterable && this.showPrefix
      };
    },
    // 3.4.0, global setting customArrow 有值时，arrow 赋值空
    arrowType () {
      const config = this.globalConfig;
      let type = 'arrow-down';
      if (config) {
        if (config.select.customArrow) {
          type = '';
        } else if (config.select.arrow) {
          type = config.select.arrow;
        }
      }
      return type;
    },
    // 3.4.0, global setting
    customArrowType () {
      const config = this.globalConfig;
      let type = '';
      if (config) {
        if (config.select.customArrow) {
          type = config.select.customArrow;
        }
      }
      return type;
    },
    showPrefix () {
      const prefix = this.$slots.prefix && this.$slots.prefix();
      let visible = false;
      if (prefix) {
        visible = prefix[0].children.length > 0;
      }
      return visible || this.prefix
    },
    // 3.4.0, global setting
    arrowSize () {
      const config = this.globalConfig;
      let size = '';
      if (config) {
        if (config.select.arrowSize) {
          size = config.select.arrowSize;
        }
      }
      return size;
    }
  },
  methods: {
    onInputFocus () {
      this.$emit('on-input-focus');
    },
    onInputBlur () {
      if (this.showCreateItem) return;
      if (!this.values.length) this.query = '';  // #5155
      this.$emit('on-input-blur');
    },
    removeTag (val, e) {
      // console.log("in select head")
      const value = toRaw(val)
      if(e) e.stopPropagation()
      if (this.disabled) return false;
      this.SelectInstance.handleOnSelectSelected(value);
      this.onRemoveTag?.(value);
    },
    resetInputState () {
      this.inputLength = this.$refs.input.value.length * 12 + 20;
      this.$emit('on-keydown');
    },
    handleInputDelete (e) {
      const targetValue = e.target.value;
      if (this.multiple && this.selectedMultiple.length && this.query === '' && targetValue === '') {
        this.removeTag(this.selectedMultiple[this.selectedMultiple.length - 1]);
      }
    },
    handleInputEnter (e) {
      this.$emit('on-enter');
      // #926
      if (this.showCreateItem) {
        e.stopPropagation()
      };
    },
    onHeaderClick (e) {
      if (this.filterable && e.target === this.$el){
        this.$refs.input.focus();
      }
    },
    onClear () {
      this.$emit('on-clear');
    }
  },
  watch: {
    values ([value]) {
      // console.log("value change in select head", Date.now())
      if (!this.filterable) return;
      this.preventRemoteCall = true;
      if (this.multiple){
        this.query = '';
        this.preventRemoteCall = false; // this should be after the query change setter above
        return;
      }
      // #982
      if (typeof value === 'undefined' || value === '' || value === null) this.query = '';
      else this.query = value.label;
      nextTick(() => this.preventRemoteCall = false); // this should be after the query change setter above
    },
    query (val) {
      if (this.preventRemoteCall) {
        this.preventRemoteCall = false;
        return;
      }
      this.$emit('on-query-change', val);
    },
    queryProp (query ){
      if (query !== this.query) this.query = query;
    },
  }
};
</script>